var AV = require('leanengine');
var async = require('async');
//订单有关的模型
var orderM = require('../models/order');
var cartM = require('../models/cart.js');
var addrM = require('../models/address.js');
var UserM = require('../models/modUser.js');
var AddrM = require('../models/address');
var CouponM = require('../models/coupon');
var commonM = require('../models/common');
var productM = require('../models/product');

var FlowM = AV.Object.extend("OrderFlow");
var AmountFlowM = AV.Object.extend("AmountFlow");



module.exports = {

    getOrderListByAll:function(req,res,next){
        //我的全部订单

        //var userid = req.params.userid;         //获取用户编号
        var userid = req.AV.user.id;              //获取用户编号

        orderM.getOrderListByAll(userid).then(function(order){
            res.render('order/myOrderByAll',{title:'我的全部订单',order:order});
        }).catch(function(err){
            res.error(err);
        });
    },
    getOrderListByPay:function(req,res,next){
        //我的待付款订单

        //var userid = req.params.userid;         //获取用户编号
        var userid = req.AV.user.id;              //获取用户编号

        orderM.getOrderListByAll(userid).then(function(order){
            res.render('order/myOrderByPay',{title:'我的待付款订单',order:order});
        }).catch(function(err){
            res.error(err);
        });

    },
    getOrderListByReceived:function(req,res,next){
        //我的待收货订单

        //var userid = req.params.userid;         //获取用户编号
        var userid = req.AV.user.id;              //获取用户编号

        async.waterfall([
            //通过cname获取cid
            function(callback){
                ClzM.getByName(cname).then(function(clz){
                    callback(null,clz);
                });
            },
            //通过cid获取商品列表
            //clz 指向前面一个函数的输出值
            function(clz,callback){
                ProM.list(clz.id,page).then(function(list){
                    callback(null,{classify:clz,list:list});
                }).catch(function(err){
                    //TODO:错误的处理
                });
            }
        ],function(err,result){
            if(err){
                //TODO:
                return;
            }

            res.render('order/myOrderByReceived',{title:result.classify.get('intro'),list:result.list});
        });

    },
    getOrderListByEvaluation:function(req,res,next){
        //我的待评价订单

        //var userid = req.params.userid;         //获取用户编号
        var userid = req.AV.user.id;              //获取用户编号

        async.waterfall([
            //通过cname获取cid
            function(callback){
                ClzM.getByName(cname).then(function(clz){
                    callback(null,clz);
                });
            },
            //通过cid获取商品列表
            //clz 指向前面一个函数的输出值
            function(clz,callback){
                ProM.list(clz.id,page).then(function(list){
                    callback(null,{classify:clz,list:list});
                }).catch(function(err){
                    //TODO:错误的处理
                });
            }
        ],function(err,result){
            if(err){
                //TODO:
                return;
            }

            res.render('order/myOrderByEvaluation',{title:result.classify.get('intro'),list:result.list});
        });

    },
    getOrderListByComplete:function(req,res,next){
        //我的已完成订单

        //var userid = req.params.userid;         //获取用户编号
        var userid = req.AV.user.id;              //获取用户编号

        async.waterfall([
            //通过cname获取cid
            function(callback){
                ClzM.getByName(cname).then(function(clz){
                    callback(null,clz);
                });
            },
            //通过cid获取商品列表
            //clz 指向前面一个函数的输出值
            function(clz,callback){
                ProM.list(clz.id,page).then(function(list){
                    callback(null,{classify:clz,list:list});
                }).catch(function(err){
                    //TODO:错误的处理
                });
            }
        ],function(err,result){
            if(err){
                //TODO:
                return;
            }

            res.render('order/myOrderByComplete',{title:result.classify.get('intro'),list:result.list});
        });
    },
    /**
     * 跳转到确认订单页面
     * Created by James at 2015-09-07
     * @param req
     * @param res
     * @param next
     */
    confirmOrder:function(req,res,next){

        var userid = req.AV.user.id;              //获取用户编号
        var openid = req.AV.user.get('openid');   //获取openid

        var aid = req.params.aid;           //用户地址编号

        var total = 0;
        var goods = [];
        var str = "";
        var level_rate = 1;
        var dzje = 0;
        var fdzje = 0;

        if(aid == 0){
            //用户地址为空，代表是从购物车模块跳转过来的
            AddrM.listAddress(userid).then(function(obj){
                if(obj.length == 0){
                    //没有地址，则跳转到新增地址页面
                    var url = '/order/confirmOrder/';
                    res.redirect('/user/center/address?back='+url);
                }else{
                    async.waterfall([
                        //通过userid获取用户订单的商品
                        function(callback){
                            cartM.getProductList(userid,true).then(function(result){
                                var psid;
                                var specArray;
                                var imgArray;
                                if (result.rows > 0) {
                                    for (x in result.data) {
                                        psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                                        specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                                        imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                                        goods.push(
                                            {
                                                pid:        result.data[x].get('pid'),
                                                pname:      result.data[x].get('product').get('name'),
                                                sid:        result.data[x].get('psid'),
                                                cid:        result.data[x].get('product').get('cid'),
                                                sname:      specArray[psid]['name'],
                                                price:      parseInt(specArray[psid]['grprice']),
                                                size:       parseInt(result.data[x].get('number')),
                                                img:        imgArray[0],
                                                point:      specArray[psid]['point'],
                                                pointRate:  specArray[psid]['pointRate'],
                                                isPoint:    specArray[psid]['isPoint'],
                                                isDiscount: specArray[psid]['isDiscount']
                                            }
                                        )

                                        if(specArray[psid]['isDiscount'] == '1'){
                                            dzje = dzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                        }

                                        if(specArray[psid]['isDiscount'] == '0'){
                                            fdzje = fdzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                        }
                                    }
                                }
                                callback(null,goods,dzje,fdzje);
                            });
                        },
                        //获取购物车商品总价
                        function(cartList,dzje,fdzje,callback){
                            cartM.getGoodsPrice(userid).then(function (result) {
                                total = result.GoodsPrice;
                                callback(null,cartList,total,dzje,fdzje);

                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        },
                        //获取平台活动
                        function(cartList,total,dzje,fdzje,callback){
                            cartM.getActivityRuleMJ(total).then(function (result) {
                                for (x in result.ruleList) {
                                    if(result.ruleList[x].get('checked') == true){
                                        str = result.ruleList[x].get('name');
                                    }
                                }
                                var discountPrice=result.discountPrice;
                                callback(null,cartList,total,discountPrice,str,dzje,fdzje);
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        },
                        //获取用户余额
                        function(cartList,total,discountPrice,str,dzje,fdzje,callback){
                            UserM.getAmountByOpenID(openid).then(function (result) {
                                callback(null,cartList,total,discountPrice,str,dzje,fdzje,result);
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        },
                        //获取用户等级
                        function(cartList,total,discountPrice,str,dzje,fdzje,balance,callback){
                            UserM.getLevelByOpenID(openid).then(function (level_id){
                                if(level_id == 2){
                                    level_rate = 1;
                                }else if(level_id == 3){
                                    level_rate = 0.95;
                                }else if(level_id == 4){
                                    level_rate = 0.92;
                                }else if(level_id == 5){
                                    level_rate = 0.9;
                                }else if(level_id == 1){
                                    level_rate = 0.85;
                                }
                                callback(null,{cartList:cartList,total:total,dzje:dzje,fdzje:fdzje,discountPrice:discountPrice,str:str,level_rate:level_rate,balance:balance});
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        }
                    ],function(err,result){
                        if(err){
                            res.error(err);
                        }
                        if(result.cartList.length == 0){
                            //如果没有商品，则跳转到首页
                            res.redirect('/');
                        }else{
                            res.render('order/confirmOrder',{title:'确认订单',cart:result.cartList,level_rate:result.level_rate,total:result.total,dzje:result.dzje,fdzje:result.fdzje,discountPrice:result.discountPrice,str:result.str,balance:result.balance,aid:aid});
                        }
                    });
                }
            }).catch(function(err){
                res.error(err);
            });
        }else{
            //用户地址不为空，代表是从我的地址模块跳转过来的
            async.waterfall([
                //通过userid获取用户订单的商品
                function(callback){
                    cartM.getProductList(userid,true).then(function(result){
                        var psid;
                        var specArray;
                        var imgArray;
                        if (result.rows > 0) {
                            for (x in result.data) {
                                psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                                specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                                imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                                goods.push(
                                    {
                                        pid:        result.data[x].get('pid'),
                                        pname:      result.data[x].get('product').get('name'),
                                        sid:        result.data[x].get('psid'),
                                        cid:        result.data[x].get('product').get('cid'),
                                        sname:      specArray[psid]['name'],
                                        price:      parseInt(specArray[psid]['grprice']),
                                        size:       parseInt(result.data[x].get('number')),
                                        img:        imgArray[0],
                                        point:      specArray[psid]['point'],
                                        pointRate:  specArray[psid]['pointRate'],
                                        isPoint:    specArray[psid]['isPoint'],
                                        isDiscount: specArray[psid]['isDiscount']
                                    }
                                )

                                if(specArray[psid]['isDiscount'] == '1'){
                                    dzje = dzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                }

                                if(specArray[psid]['isDiscount'] == '0'){
                                    fdzje = fdzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                }
                            }
                        }
                        callback(null,goods,dzje,fdzje);
                    });
                },
                //获取购物车商品总价
                function(cartList,dzje,fdzje,callback){
                    cartM.getGoodsPrice(userid).then(function (result) {
                        total = result.GoodsPrice;
                        callback(null,cartList,total,dzje,fdzje);

                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                },
                //获取平台活动
                function(cartList,total,dzje,fdzje,callback){
                    cartM.getActivityRuleMJ(total).then(function (result) {
                        for (x in result.ruleList) {
                            if(result.ruleList[x].get('checked') == true){
                                str = result.ruleList[x].get('name');
                            }
                        }
                        var discountPrice=result.discountPrice;
                        callback(null,cartList,total,discountPrice,str,dzje,fdzje);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                },
                //获取用户余额
                function(cartList,total,discountPrice,str,dzje,fdzje,callback){
                    UserM.getAmountByOpenID(openid).then(function (result) {
                        callback(null,cartList,total,discountPrice,str,dzje,fdzje,result);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                },
                //获取用户等级
                function(cartList,total,discountPrice,str,dzje,fdzje,balance,callback){
                    UserM.getLevelByOpenID(openid).then(function (level_id){
                        if(level_id == 2){
                            level_rate = 1;
                        }else if(level_id == 3){
                            level_rate = 0.95;
                        }else if(level_id == 4){
                            level_rate = 0.92;
                        }else if(level_id == 5){
                            level_rate = 0.9;
                        }else if(level_id == 1){
                            level_rate = 0.85;
                        }
                        callback(null,{cartList:cartList,total:total,dzje:dzje,fdzje:fdzje,discountPrice:discountPrice,str:str,level_rate:level_rate,balance:balance});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            ],function(err,result){
                if(err){
                    res.error(err);
                }

                if(result.cartList.length == 0){
                    //如果没有商品，则跳转到首页
                    res.redirect('/');
                }else{
                    res.render('order/confirmOrder',{title:'确认订单',cart:result.cartList,level_rate:result.level_rate,total:result.total,dzje:result.dzje,fdzje:result.fdzje,discountPrice:result.discountPrice,str:result.str,balance:result.balance,aid:aid});
                }
            });
        }
    },
    confirmOrderUI:function(req,res,next){
        //确认订单
        res.render('order/confirmOrder',{title:'确认订单'});
    },
    /**
     * 生成订单
     * Created by James at 2015-09-07
     * @param req
     * @param res
     * @param next
     */
    addOrder:function(req,res,next){
        var data = req.query;//获取表单参数

        var par = data.par;

        delete data.par;

        var finalAmount = parseFloat(data.finalAmount);
        var total = parseFloat(data.total);
        var payway = data.payway;
        var couponId = data.couponId;
        var type = 0;           //0:普通订单 5：预售订单
        var code = "";         //商品活动标题简码
        var str ;
        var balance = 0;
        var online = 0;
        var onlinetype = '';
        var status = 1000;

        if(payway =='ye_pay'){
            str = '余额支付';
            balance = finalAmount;
            status = 2000;

        }else if(payway =='wx_pay'){
            str = '微信支付';
            online = finalAmount;
            onlinetype = '微信支付';
            status = 1000;
        }else{
            //payway =='hdfk_pay'
            str = '货到付款';
            status = 2000;
        }

        var uid = req.AV.user.id;
        var goods = new Array();
        var timestamp=new Date().getTime();
        var orderid = 'O'+timestamp;

        async.waterfall([
            //通过uid获取用户订单的商品
            function(callback){
                cartM.getProductList(uid,true).then(function(result){
                    var psid;
                    var specArray;
                    var imgArray;
                    var points = 0;
                    var dzje = 0;

                    if (result.rows > 0) {
                        for (x in result.data) {
                            psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                            specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                            imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                            goods.push(
                                {
                                    pid:        result.data[x].get('pid'),
                                    pname:      result.data[x].get('product').get('name'),
                                    sid:        result.data[x].get('psid'),
                                    cid:        result.data[x].get('product').get('cid'),
                                    sname:      specArray[psid]['name'],
                                    price:      parseInt(specArray[psid]['grprice']),
                                    size:       parseInt(result.data[x].get('number')),
                                    img:        imgArray[0],
                                    point:      specArray[psid]['point'],
                                    pointRate:  specArray[psid]['pointRate'],
                                    isPoint:    specArray[psid]['isPoint'],
                                    isDiscount: specArray[psid]['isDiscount']
                                }
                            );

                            if(specArray[psid]['isDiscount'] == '1'){
                                dzje = dzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                            }
                            points = points+(parseInt(specArray[psid]['point']) * parseInt(result.data[x].get('number')));
                        }
                        callback(null,goods,points,dzje,result);
                    }else{
                        callback({code:505});   //code:505 购物车内已无商品，请刷新页面
                    }
                });
            },
            //获取该订单是否活动订单
            function(cartList,points,dzje,result,callback){

                    var p_id = result.data[0].get('pid')+'';
                    var s_id = result.data[0].get('psid')+'';
                    var c_id =result.data[0].get('product').get('cid');

                    commonM.getLimitCondition(s_id,p_id,c_id,uid).then(function(mm){

                        var normalProduct = mm.finalResult.normalProduct;
                        var isInDate = mm.finalResult.isInDate;
                        var isLoop = mm.finalResult.isLoop;
                        var isInTime = mm.finalResult.isInTime;
                        //console.log(mm.finalResult);

                        if(normalProduct == 0 && isInDate == 1){
                            if(isLoop == 1){
                                if(isInTime == 1){
                                    type = 5;           //预售商品
                                    code = mm.finalResult.actInfo.get('code');
                                }else{
                                    type = 0;           //活动商品,但不在规定时间内
                                }
                            }else{
                                type = 5;           //活动商品
                                code = mm.finalResult.actInfo.get('code');
                            }
                        }else{
                            type = 0;           //正常商品
                        }
                        callback(null,goods,points,dzje,type,code,mm);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
            },
            //通过用户地址编号获取用户地址
            function(cartList,points,dzje,type,code,actInfo,callback){
                addrM.getAddressByObjId(data.addrId).then(function(obj){
                    callback(null,cartList,obj,points,dzje,type,code,actInfo);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //生成订单
            function(cartList,obj,points,dzje,type,code,actInfo,callback){

                //console.log('===type:'+type);
                //console.log('===code:'+code);

                if(type == 5 && code == 'zqys'){
                    //预售活动
                    type = 5;
                }else{
                    type = 0;
                }

                data['payway']=str;

                if(par>0){
                    data['description']=str+':'+finalAmount+' 元,优惠券抵扣:'+parseFloat(par).toFixed(2)+'元';
                }else{
                    data['description']=str+':'+finalAmount+' 元';
                }

                data['uid']=uid;
                data['finalAmount']=finalAmount;
                data['total']=total;
                data['dzje']=dzje;
                data['balance']=balance;
                data['online']=online;
                data['onlinetype']=onlinetype;
                data['type']=type;
                data['orderid']=orderid;
                data['status']=status;
                data['point']=points;
                data['canceltime']=timestamp+(2*60*60);
                data['goods']=cartList;
                data['address']=obj.toJSON();
                var jsontext = '[{"way":"'+str+'","pay":'+finalAmount+'}]';
                data['details']=JSON.parse(jsontext);

                if(str=="微信支付"){
                    data['syncStatus']=0;
                }else {
                    data['syncStatus']=1;
                    data['paytime']=timestamp;
                }

                data['location']= new AV.GeoPoint({latitude: 39.9, longitude: 116.4});

                orderM.addOrder(data).then(function(obj){
                    //保存成功
                    callback(null,cartList,actInfo);
                }).catch(function(err){
                    //保存失败
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //向limitbuyrecord表中插入数据
            function(cartList,actInfo,callback){

                var normalProduct = actInfo.finalResult.normalProduct;
                var isInDate = actInfo.finalResult.isInDate;
                var isLoop = actInfo.finalResult.isLoop;
                var isInTime = actInfo.finalResult.isInTime;
                if(normalProduct == 0 && isInDate == 1){
                    if(isLoop == 1){
                        if(isInTime == 1){
                            orderM.addToLimitRecord(uid,orderid,cartList[0].pid,cartList[0].sid,cartList[0].cid,actInfo.finalResult.actInfo.id).then(function(res){

                                return callback(null);
                            }).catch(function(err){
                                callback(err);
                            });
                        }else{
                            return callback(null);
                        }
                    }else{
                        orderM.addToLimitRecord(uid,orderid,cartList[0].pid,cartList[0].sid,cartList[0].cid,actInfo.finalResult.actInfo.id).then(function(res){

                            //console.log("向limitbuyrecord表中插入数据----end");
                            return callback(null);
                        }).catch(function(err){
                            callback(err);
                        });
                    }
                }else{
                    callback(null);
                }

            },
            //更新用户余额
            function(callback){
                if(payway =='ye_pay'){
                    UserM.minusAmount(uid,finalAmount*100).then(function(result){

                        callback(null,result.ysye,result.dqye);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,0,0);
                }
            },
            //更新用户余额流水
            function(ysye,dqye,callback){
                if(payway =='ye_pay'){
                    var amountflow = new AmountFlowM();
                    amountflow.set('newamount',finalAmount);
                    amountflow.set('beforeamount',ysye);
                    amountflow.set('afteramount',dqye);
                    amountflow.set('userid',uid);
                    amountflow.set('content','订单'+orderid+'使用余额支付,扣除账户余额'+finalAmount+'元.');
                    amountflow.save().then(function(result){
                        callback(null);
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null);
                }
            },
            //删除购物车商品
            function(callback){
                cartM.delCart(uid).then(function(result){
                    callback(null);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });               　
            },

            //生成流水信息
            function(callback){
                if(payway =='ye_pay' || payway =='hdfk_pay'){
                    var flow = new FlowM();
                    flow.set('orderid',orderid);
                    flow.set('amount',finalAmount);
                    flow.set('paytime',new Date().getTime());
                    flow.set('userid',uid);
                    flow.set('content','使用'+str+finalAmount+'元.');
                    flow.save().then(function(result){
                        callback(null);
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null);
                }
            },

            //更新优惠券使用状态
            function(callback){
                if(!couponId){
                    callback(null,{code:0,orderid:orderid,fee:finalAmount*100});
                }else{
                    CouponM.updateUserCoupon(couponId,1).then(function(result){
                        callback(null,{code:0,orderid:orderid,fee:finalAmount*100});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    },
    /**
     * 微信支付回调接口
     * Created by James at 2015-09-10
     * @param req
     * @param res
     * @param next
     */
    notify:function(req,res,next){
        var data = req.query;//获取表单参数

        var orderid = data.orderid;
        var je = parseInt(data.je+"")*100;
        var payWay = data.payWay;

        orderM.notify(orderid,je,payWay).then(function(order){
            res.render('order/myOrderByAll',{title:'我的全部订单',order:order});
        }).catch(function(err){
            res.error(err);
        });

        async.waterfall([
            //微信支付回调接口
            function(callback){
                orderM.notify(orderid,je,payWay).then(function(obj){
                    callback(null,obj.userid,obj.point,je);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户余额
            function(userid,point,je,callback){
                UserM.minusAmount(uid,je).then(function(result){
                    callback(null,uid,point);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户积分
            function(userid,point,callback){
                UserM.updatePoints(userid,point).then(function(result){
                    callback(null,{code:0});
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    },
    setOrderCancel:function(req,res,next){
        //撤销订单

        var objectId = req.params.objectId;         //获取objectId

        orderM.setOrderCancel(objectId).then(function(order){
            res.redirect('/user/history/0');
        }).catch(function(err){
            res.json(err);
        });
    },
    againPay:function(req,res,next){
        //订单重新付款

        var data = req.query;//获取表单参数

        var orderid = data.orderid;             //获取订单编号
        var payWay = data.payway;               //获取支付方式

        orderM.againPay(orderid,payWay).then(function(result){
            res.json(result);
        }).catch(function(err){
            res.json(err);
        });
    },
};